package com.ruan.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruan.entity.Goods;
import com.ruan.entity.Result;
import com.ruan.query.GoodsQuery;
import com.ruan.service.GoodsService;
import com.ruan.service.GoodsTypeService;
import com.ruan.utils.OssUtil;
import com.ruan.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @ClassName:GoodsController
 * @Author:阮昇
 * @Description:
 * @Datetime: 2023/7/1 18:23
 **/
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @PostMapping("/uploadGoodsPicture")
    public Result uploadGoodsPicture(MultipartFile file) throws IOException {
        //获取上传的文件名
        String fileName = file.getOriginalFilename();

        //产生新的文件名，时间戳+原先文件名后缀
        String newFileName = System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf('.'));

        String path = "goodsPicture/";

        String avatar = OssUtil.upload(newFileName, file.getInputStream(),path);

        return new Result(200,avatar);
    }

    @PostMapping("/addGoods")
    public Result addGoods(Goods goods){
        return goodsService.addGoods(goods);
    }

    @PostMapping("/getGoodsList")
    public Result getGoodsList(GoodsQuery goodsQuery){
        //开启分页
        PageHelper.startPage(goodsQuery.getPageNum(),goodsQuery.getPageSize());

        List<GoodsVo> goodsVoList = goodsService.getGoodsList(goodsQuery);

        //当前页，下一页，上一页，首页，尾页。。。。需要一个类进行封装，
        PageInfo<GoodsVo> goodsVoPageInfo = new PageInfo<>(goodsVoList);

        return new Result(200,goodsVoPageInfo);
    }

    @PostMapping("/editGoods")
    public Result editGoods(Goods goods){
        return goodsService.editGoods(goods);
    }

    @RequestMapping("/deleteGoods/{id}")
    public Result deleteGoods(@PathVariable Integer id){
        return goodsService.deleteGoods(id);
    }

    @PostMapping("/deleteGoodsByIds")
    public Result deleteGoodsByIds(@RequestParam("ids[]") Integer[] ids){
        return goodsService.deleteGoodsByIds(ids);
    }

    @RequestMapping("/getGoodsById/{id}")
    public GoodsVo getGoodsById(@PathVariable Integer id){
        return goodsService.getGoodsById(id);
    }

    @RequestMapping("/addSales/{id}/{count}")
    public void addSales(@PathVariable Integer id, @PathVariable Integer count){
        goodsService.addSales(id,count);
    }
}
